define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'newhouse/newhouse/index' + location.search,
                    add_url: 'newhouse/newhouse/add',
                    edit_url: 'newhouse/newhouse/edit',
                    del_url: 'newhouse/newhouse/del',
                    multi_url: 'newhouse/newhouse/multi',
                    table: 'newhouse',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'weigh',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title')},
                        {field: 'region', title: __('Region'), searchList: {"0":__('Region 0'),"1":__('Region 1'),"2":__('Region 2'),"3":__('Region 3'),"4":__('Region 4'),"5":__('Region 5'),"6":__('Region 6'),"7":__('Region 7'),"8":__('Region 8'),"9":__('Region 9')}, formatter: Table.api.formatter.normal},
                        {field: 'image', title: __('Cover'), operate: false, events: Controller.api.events.image, formatter: Controller.api.formatter.image},
                        {field: 'recommend', title: __('Recommend'), searchList: {"0":__('Recommend 0'),"1":__('Recommend 1')}, formatter: Controller.api.formatter.recommend},
                        {field: 'flag', title: __('Flag'), searchList: {"0":__('Flag 0'),"1":__('Flag 1')}, formatter: Controller.api.formatter.flag},
                        {field: 'partner', title: __('Partner'), searchList: {"0":__('Partner 0'),"1":__('Partner 1')}, formatter: Controller.api.formatter.partner},
                        {field: 'admin.nickname', title: __('Admin.nickname')},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, buttons: [
                                {
                                    name: 'lp',
                                    text: '楼盘构成',
                                    icon: 'fa fa-building',
                                    classname: 'btn btn-xs btn-default btn-addtabs',
                                    url: function (row, column) {
                                        return "newhouse/structure?newhouse_id=" + row.id;
                                    }
                                }, {
                                    name: 'hx',
                                    text: '户型',
                                    icon: 'fa fa-image',
                                    classname: 'btn btn-xs btn-default btn-addtabs',
                                    url: function (row, column) {
                                        return "newhouse/layout?newhouse_id=" + row.id;
                                    }
                                }, {
                                    name: 'sj',
                                    text: '实景',
                                    icon: 'fa fa-image',
                                    classname: 'btn btn-xs btn-default btn-addtabs',
                                    url: function (row, column) {
                                        return "newhouse/realscene?newhouse_id=" + row.id;
                                    }
                                }, {
                                    name: 'dt',
                                    text: '动态',
                                    icon: 'fa fa-twitch',
                                    classname: 'btn btn-xs btn-default btn-addtabs',
                                    url: function (row, column) {
                                        return "newhouse/dynamic?newhouse_id=" + row.id;
                                    }
                                }, {
                                    name: 'jg',
                                    text: '价格',
                                    icon: 'fa fa-jpy',
                                    classname: 'btn btn-xs btn-default btn-addtabs',
                                    url: function (row, column) {
                                        return "newhouse/price?newhouse_id=" + row.id;
                                    }
                                }], events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
            $(".btn-add").data("area", ["90%", "90%"]);
            $(".btn-edit").data("area", ["90%", "90%"]);
            //当内容渲染完成给编辑按钮添加`data-area`属性
            table.on('post-body.bs.table', function (e, settings, json, xhr) {
                $(".btn-editone").data("area", ["90%", "90%"]);
            });
            // 绑定TAB事件
            $('.panel-heading .nav-tabs a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
                var field = $(this).data("field");
                var value = $(this).data("value");
                var options = table.bootstrapTable('getOptions');
                options.pageNumber = 1;
                options.queryParams = function (params) {
                    var filter = {};
                    if (value !== '') {
                        filter[field] = value;
                    }
                    params.filter = JSON.stringify(filter);
                    return params;
                };
                table.bootstrapTable('refresh', {});
                return false;
            });
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'newhouse/newhouse/recyclebin' + location.search,
                pk: 'id',
                sortName: 'weigh',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left'},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'newhouse/newhouse/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'newhouse/newhouse/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                $("[data-toggle='addresspicker']").data("callback", function(res) {
                    if (res.address != '' && res.lat != '' && res.lng != '') {
                        $(this).blur();
                        $('#c-addresstext').val(res.lng+','+res.lat);
                    }
                });
                $(document).on('click', "input[name='row[covertype]']", function () {
                    var val = $(this).val();
                    if (val == 1) {
                        $('#house').hide();
                        $('#business').show();
                    } else {
                        $('#business').hide();
                        $('#house').show();
                    }
                });

                Form.api.bindevent($("form[role=form]"));

                var house_image_input = $('#plupload-house_image').data("input-id") ? $('#plupload-house_image').data("input-id") : "";
                var house_image_preview = $('#plupload-house_image').data("preview-id") ? $('#plupload-house_image').data("preview-id") : "";
                if (house_image_preview) {
                    $(document.body).off("click", "#" + house_image_preview + " .btn-trash");
                    // 监听事件
                    $("#plupload-house_image").data("upload-success", function(data, ret) {
                        //这里进行后续操作
                        $(this).hide();
                    });
                    // 移除按钮事件
                    $(document.body).on("click", "#" + house_image_preview + " .btn-trash", function () {
                        var that = $(this);
                        var path = $("#" + house_image_preview + " [data-url]");
                        Layer.confirm('是否删除该图片？（删除后不可恢复）',
                            {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                            function (index) {
                                var options = {
                                    url: 'newhouse/newhouse/delUpload',
                                    data: {
                                        houseid: $("#plupload-house_image").data('houseid'),
                                        dbfield: $("#plupload-house_image").data('field'),
                                        path: path.data("url")
                                    }
                                }
                                Fast.api.ajax(options, function () {
                                    $("#" + house_image_input).val('');
                                    that.closest("li").remove();
                                    $("#plupload-house_image").show();
                                    Layer.close(index);
                                });
                            }
                        );
                    });
                }
                if ($("#" + house_image_input).val() != '') {
                    $("#" + house_image_input).hide();
                }

                var business_image_input = $('#plupload-business_image').data("input-id") ? $('#plupload-business_image').data("input-id") : "";
                var business_image_preview = $('#plupload-business_image').data("preview-id") ? $('#plupload-business_image').data("preview-id") : "";
                if (business_image_preview) {
                    $(document.body).off("click", "#" + business_image_preview + " .btn-trash");
                    // 监听事件
                    $("#plupload-business_image").data("upload-success", function(data, ret) {
                        //这里进行后续操作
                        $(this).hide();
                    });
                    // 移除按钮事件
                    $(document.body).on("click", "#" + business_image_preview + " .btn-trash", function () {
                        var that = $(this);
                        var path = $("#" + business_image_preview + " [data-url]");
                        Layer.confirm('是否删除该图片？（删除后不可恢复）',
                            {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                            function (index) {
                                var options = {
                                    url: 'newhouse/newhouse/delUpload',
                                    data: {
                                        houseid: $("#plupload-business_image").data('houseid'),
                                        dbfield: $("#plupload-business_image").data('field'),
                                        path: path.data("url")
                                    }
                                }
                                Fast.api.ajax(options, function () {
                                    $("#" + business_image_input).val('');
                                    that.closest("li").remove();
                                    $("#plupload-business_image").show();
                                    Layer.close(index);
                                });
                            }
                        );
                    });
                }
                if ($("#" + business_image_input).val() != '') {
                    $("#" + business_image_input).hide();
                }

                var image_input = $('#plupload-image').data("input-id") ? $('#plupload-image').data("input-id") : "";
                var image_preview = $('#plupload-image').data("preview-id") ? $('#plupload-image').data("preview-id") : "";
                if (image_preview) {
                    $(document.body).off("click", "#" + image_preview + " .btn-trash");
                    // 监听事件
                    $("#plupload-image").data("upload-success", function(data, ret) {
                        //这里进行后续操作
                        $(this).hide();
                    });
                    // 移除按钮事件
                    $(document.body).on("click", "#" + image_preview + " .btn-trash", function () {
                        var that = $(this);
                        var path = $("#" + image_preview + " [data-url]");
                        Layer.confirm('是否删除该图片？（删除后不可恢复）',
                            {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                            function (index) {
                                var options = {
                                    url: 'newhouse/newhouse/delUpload',
                                    data: {
                                        houseid: $("#plupload-image").data('houseid'),
                                        dbfield: $("#plupload-image").data('field'),
                                        path: path.data("url")
                                    }
                                }
                                Fast.api.ajax(options, function () {
                                    $("#" + image_input).val('');
                                    that.closest("li").remove();
                                    $("#plupload-image").show();
                                    Layer.close(index);
                                });
                            }
                        );
                    });
                }
                if ($("#" + image_input).val() != '') {
                    $("#" + image_input).hide();
                }
            },
            events: {
                image: {
                    'click .img-center': function (e, value, row, index) {
                        if (row.covertype == 0) {
                            value = Fast.api.cdnurl(row.house_image);
                        } else if(row.covertype == 1) {
                            value = Fast.api.cdnurl(row.business_image);
                        } else {
                            value = '/assets/img/blank.gif';
                        }
                        var data = [];
                        value = value.toString().split(",");
                        $.each(value, function (index, value) {
                            data.push({
                                src: Fast.api.cdnurl(value),
                            });
                        });
                        Layer.photos({
                            photos: {
                                "start": $(this).parent().index(),
                                "data": data
                            },
                            anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                        });
                    },
                }
            },
            formatter: {
                image: function (value, row, index) {
                    if (row.covertype == 0) {
                        value = Fast.api.cdnurl(row.house_image);
                    } else if(row.covertype == 1) {
                        value = Fast.api.cdnurl(row.business_image);
                    } else {
                        value = '/assets/img/blank.gif';
                    }
                    var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
                    return '<a href="javascript:void(0);"><img class="' + classname + '" src="' + value + '" /></a>';
                },
                recommend: function (value, row, index) {
                    return '<a class="btn-change text-success" data-url="'+$.fn.bootstrapTable.defaults.extend.multi_url+'" data-id="' + row.id + '" data-params="recommend=' + (row.recommend == '0' ? '1' : '0') + '"><i class="fa ' + (row.recommend == '0' ? 'fa-toggle-off' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                flag: function (value, row, index) {
                    return '<a class="btn-change text-success" data-url="'+$.fn.bootstrapTable.defaults.extend.multi_url+'" data-id="' + row.id + '" data-params="flag=' + (row.flag == '0' ? '1' : '0') + '"><i class="fa ' + (row.flag == '0' ? 'fa-toggle-off' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                partner: function (value, row, index) {
                    return '<a class="btn-change text-success" data-url="'+$.fn.bootstrapTable.defaults.extend.multi_url+'" data-id="' + row.id + '" data-params="partner=' + (row.partner == '0' ? '1' : '0') + '"><i class="fa ' + (row.partner == '0' ? 'fa-toggle-off' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                },
                title: function (value, row, index) {
                    return '<a href="https://www.0759home.com/newhouse/info/id/' + row.id + '.html" target="_blank">' + value + '</a>';
                }
            }
        }
    };
    return Controller;
});
